package top.knos.od.service;

import jakarta.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.knos.od.common.PageVo;
import top.knos.od.his.domain.FeeItem;
import top.knos.od.his.repository.FeeItemRepository;
import top.knos.od.support.PageVoUtil;
import top.knos.od.vo.DeleteStringIdReq;
import top.knos.od.vo.FeeItemReq;
import top.knos.od.vo.FeeItemVo;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class FeeItemService {
    @Autowired
    private FeeItemRepository feeItemRepository;

    

    /**
     * 保存
     */
    public void save(FeeItemVo feeItemVo) {
        FeeItem feeItem = new FeeItem();

        feeItem.setName(feeItemVo.getName());
        feeItem.setUnit(feeItemVo.getUnit());
        feeItem.setPrice(feeItemVo.getPrice());
        feeItem.setType(feeItemVo.getType());


        
        feeItemRepository.save(feeItem);
    }

    /**
     * 删除
     */
    public void delete(DeleteStringIdReq deleteReq) {
        feeItemRepository.deleteAllById(deleteReq.getIds());
    }

    /**
     * 修改
     */
    public void update(FeeItemVo feeItemVo) {

        FeeItem feeItem = feeItemRepository.getReferenceById(feeItemVo.getId());
        feeItem.setName(feeItemVo.getName());
        feeItem.setUnit(feeItemVo.getUnit());
        feeItem.setPrice(feeItemVo.getPrice());
        feeItem.setType(feeItemVo.getType());

        feeItemRepository.save(feeItem);

    }

    /**
     * 列表查询
     */
    public PageVo<FeeItemVo> query(FeeItemReq req)  throws Exception {
        Pageable pageable = PageRequest.of(req.getCurrent()-1, req.getPageSize());
        Specification<FeeItem> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(req.getName())) {
                predicates.add(cb.like(root.get("name"), "%" + req.getName() + "%"));
            }
            if (StringUtils.hasText(req.getUnit())) {
                predicates.add(cb.equal(root.get("unit"), req.getUnit()));
            }
            if (req.getPrice() != null) {
                predicates.add(cb.equal(root.get("price"), req.getPrice()));
            }
            if (StringUtils.hasText(req.getType())) {
                predicates.add(cb.equal(root.get("type"), req.getType()));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        Page<FeeItem> feeItemPage =
                feeItemRepository.findAll(spec, pageable);
        
        return PageVoUtil.covertPageToPageVo(feeItemPage, FeeItemVo.class);
    }
}
